package com.grmasa.soundtoggle;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Icon;
import android.media.AudioManager;
import android.os.Vibrator;
import android.provider.Settings;
import android.service.quicksettings.Tile;
import android.service.quicksettings.TileService;
import android.widget.Toast;

public class SoundToggleService extends TileService {

    private final BroadcastReceiver broadcastReceiver = new Receiver();
    private MySharedPreference sharedPreference; // 用于保存和读取音量的 SharedPreferences

    class Receiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            SoundToggleService.this.updateTile();
        }
    }

    // 获取 AudioManager 实例
    private AudioManager getAudioManager() {
        return (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    }

    // 根据当前铃声模式设置图标
    private int setIcon() {
        int ringerMode = getAudioManager().getRingerMode();
        return ringerMode != 0 ? ringerMode != 1
                ? R.drawable.ic_audio_vol : R.drawable.ic_audio_ring_notif_vibrate : R.drawable.ic_audio_vol_mute;
    }

    // 更新快速设置面板的磁贴
    public void updateTile() {
        Tile qsTile = getQsTile();
        int ringerMode = getAudioManager().getRingerMode();
        String tileLabel = ringerMode != 0 ? ringerMode != 1 ? ringerMode != 2
                ? "未知模式" : "正常模式" : "震动模式" : "静音模式";
        qsTile.setContentDescription(tileLabel);
        qsTile.setLabel(tileLabel);
        qsTile.setIcon(Icon.createWithResource(this, setIcon()));
        qsTile.updateTile();
        qsTile.setState(2);
    }

    // 震动功能
    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(500);
    }

    // 点击磁贴时的操作
    public void onClick() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager.isNotificationPolicyAccessGranted()) {
            int ringerMode = getAudioManager().getRingerMode();
            int nextMode = -1;
            if (ringerMode == 0) { // 当前为静音模式
                vibrate();
                nextMode = 2; // 切换到正常模式
                restoreVolumes(); // 恢复之前保存的音量
            } else if (ringerMode == 1) { // 当前为震动模式
//                saveVolumes(); // 保存当前音量
                nextMode = 0; // 切换到静音模式
                setAllVolumesToZero(); // 将所有声音设置为0
            } else if (ringerMode == 2) { // 当前为正常模式
                saveVolumes(); // 保存当前音量
                vibrate();
                nextMode = 1; // 切换到震动模式
                setAllVolumesToZero(); // 将所有声音设置为0
            }
            getAudioManager().setRingerMode(nextMode);
        } else {
            Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            this.startActivity(intent);
        }
    }





    // 保存当前音量到 SharedPreferences
    private void saveVolumes() {
        sharedPreference = MySharedPreference.getInstance(this);
        AudioManager audioManager = getAudioManager();

        boolean useDefaultVolume = sharedPreference.getBoolean("USE_DEFAULT_VOLUME", true);

        if (useDefaultVolume) {
            // 使用预设值保存音量
            int musicVolume = (int)(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) *
                    sharedPreference.getInt("MUSIC_VOLUME", 30) / 100f);
            int ringVolume = (int)(audioManager.getStreamMaxVolume(AudioManager.STREAM_RING) *
                    sharedPreference.getInt("RING_VOLUME", 70) / 100f);
            int notificationVolume = (int)(audioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION) *
                    sharedPreference.getInt("NOTIFICATION_VOLUME", 70) / 100f);
            int alarmVolume = (int)(audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM) *
                    sharedPreference.getInt("ALARM_VOLUME", 70) / 100f);
            int systemVolume = (int)(audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM) *
                    sharedPreference.getInt("SYSTEM_VOLUME", 70) / 100f);

            sharedPreference.putInt("STREAM_MUSIC_VOLUME", musicVolume);
            sharedPreference.putInt("STREAM_RING_VOLUME", ringVolume);
            sharedPreference.putInt("STREAM_NOTIFICATION_VOLUME", notificationVolume);
            sharedPreference.putInt("STREAM_ALARM_VOLUME", alarmVolume);
            sharedPreference.putInt("STREAM_SYSTEM_VOLUME", systemVolume);
        } else {
            // 获取并保存各个声音流的音量
            int musicVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            int musicMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            if (musicVolume != 0) {
                sharedPreference.putInt("STREAM_MUSIC_VOLUME", musicVolume);
                MyLog.d("Saved STREAM_MUSIC_VOLUME: " + musicVolume + " (Max: " + musicMaxVolume + ")");
            }

            int ringVolume = audioManager.getStreamVolume(AudioManager.STREAM_RING);
            int ringMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
            if (ringVolume != 0) {
                sharedPreference.putInt("STREAM_RING_VOLUME", ringVolume);
                MyLog.d("Saved STREAM_RING_VOLUME: " + ringVolume + " (Max: " + ringMaxVolume + ")");
            }

            int notificationVolume = audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
            int notificationMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);
            if (notificationVolume != 0) {
                sharedPreference.putInt("STREAM_NOTIFICATION_VOLUME", notificationVolume);
                MyLog.d("Saved STREAM_NOTIFICATION_VOLUME: " + notificationVolume + " (Max: " + notificationMaxVolume + ")");
            }

            int alarmVolume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
            int alarmMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
            if (alarmVolume != 0) {
                sharedPreference.putInt("STREAM_ALARM_VOLUME", alarmVolume);
                MyLog.d("Saved STREAM_ALARM_VOLUME: " + alarmVolume + " (Max: " + alarmMaxVolume + ")");
            }

            int systemVolume = audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);
            int systemMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
            if (systemVolume != 0) {
                sharedPreference.putInt("STREAM_SYSTEM_VOLUME", systemVolume);
                MyLog.d("Saved STREAM_SYSTEM_VOLUME: " + systemVolume + " (Max: " + systemMaxVolume + ")");
            }
        }
    }

    // 从 SharedPreferences 中恢复音量
    private void restoreVolumes() {
        sharedPreference = MySharedPreference.getInstance(this);
        AudioManager audioManager = getAudioManager();

        // 恢复各个声音流的音量
        int musicVolume = sharedPreference.getInt("STREAM_MUSIC_VOLUME", -1);
        if (musicVolume != -1) {
            MyLog.d("Restoring STREAM_MUSIC_VOLUME: " + musicVolume);
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, musicVolume, 0);
            sharedPreference.remove("STREAM_MUSIC_VOLUME"); // 恢复后移除保存的音量
        }

        int ringVolume = sharedPreference.getInt("STREAM_RING_VOLUME", -1);
        if (ringVolume != -1) {
            MyLog.d("Restoring STREAM_RING_VOLUME: " + ringVolume);
            audioManager.setStreamVolume(AudioManager.STREAM_RING, ringVolume, 0);
            sharedPreference.remove("STREAM_RING_VOLUME");
        }

        int notificationVolume = sharedPreference.getInt("STREAM_NOTIFICATION_VOLUME", -1);
        if (notificationVolume != -1) {
            MyLog.d("Restoring STREAM_NOTIFICATION_VOLUME: " + notificationVolume);
            audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, notificationVolume, 0);
            sharedPreference.remove("STREAM_NOTIFICATION_VOLUME");
        }

        int alarmVolume = sharedPreference.getInt("STREAM_ALARM_VOLUME", -1);
        if (alarmVolume != -1) {
            MyLog.d("Restoring STREAM_ALARM_VOLUME: " + alarmVolume);
            audioManager.setStreamVolume(AudioManager.STREAM_ALARM, alarmVolume, 0);
            sharedPreference.remove("STREAM_ALARM_VOLUME");
        }

        int systemVolume = sharedPreference.getInt("STREAM_SYSTEM_VOLUME", -1);
        if (systemVolume != -1) {
            MyLog.d("Restoring STREAM_SYSTEM_VOLUME: " + systemVolume);
            audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, systemVolume, 0);
            sharedPreference.remove("STREAM_SYSTEM_VOLUME");
        }
    }

    // 将所有声音设置为0
    private void setAllVolumesToZero() {
        AudioManager audioManager = getAudioManager();
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
        audioManager.setStreamVolume(AudioManager.STREAM_RING, 0, 0);
        audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 0, 0);
        audioManager.setStreamVolume(AudioManager.STREAM_ALARM, 0, 0);
        audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, 0, 0);
    }

    public void onStartListening() {
        updateTile();
        registerReceiver(this.broadcastReceiver, new IntentFilter("android.media.RINGER_MODE_CHANGED"));
    }

    public void onStopListening() {
        unregisterReceiver(this.broadcastReceiver);
    }
}